package edu.hit;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * FIXME: 对于多条的命令例如"*1\r\n$4\r\nping\r\n*1\r\n$4\r\nping\r\n",只能处理第一条
 * {@link Protocol#processArrayBulkString(BufferedReader reader)}
 */
public class ClientHandler extends Thread{

    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }


    @Override
    public void run(){

        System.out.println(ClientHandler.currentThread());

        try{


            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());

            String command = null;

            while((command = Protocol.process(bufferedReader)) != null){

                System.out.println("command: " + command);
                String response = new CommandHandler(command).response().convert();
                System.out.println("response: " + response);
                outputStreamWriter.write(response);
                outputStreamWriter.flush();
            }





                




          //  String command = edu.hit.Protocol.process(bufferedReader);




            socket.close();
        }catch (Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();

        }


    }
}
